//
//  FMTxtPhotoViewController.m
//  FMSManagerDemo
//
//  Created by hongbao.cui on 14-12-12.
//  Copyright (c) 2014年 hongbao.cui. All rights reserved.
//

#import "FMTxtPhotoViewController.h"
#import "ApplicationUtils.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>

#define KColor  [UIColor colorWithRed:0.0/255.0 green:186.0/255.0 blue:169.0/255.0 alpha:1.0]
#define IOS7_OR_LATER   (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)?(YES):(NO))
@interface FMTxtPhotoViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    UIButton *photo;
    UIImage* edit;
    UITextView *textView;
}
@end

@implementation FMTxtPhotoViewController
-(void)photoBtnClicked:(id)sender{
    if (IOS7_OR_LATER) {
        NSString *mediaType = AVMediaTypeVideo;// Or AVMediaTypeAudio
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        // This status is normally not visible—the AVCaptureDevice class methods for discovering devices do not return devices the user is restricted from accessing.
        if(authStatus ==AVAuthorizationStatusRestricted){
            NSLog(@"Restricted");
        }else if(authStatus == AVAuthorizationStatusDenied){
            // The user has explicitly denied permission for media capture.
            NSLog(@"Denied");     //应该是这个，如果不允许的话
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请在设备设置中允许访问相机。"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            return;
        }
        else if(authStatus == AVAuthorizationStatusAuthorized){//允许访问
            // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
            NSLog(@"Authorized");
            [self showCamera];
            
        }else if(authStatus == AVAuthorizationStatusNotDetermined){
            // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
            [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
                if(granted){//点击允许访问时调用
                    //用户明确许可与否，媒体需要捕获，但用户尚未授予或拒绝许可。
                    NSLog(@"Granted access to %@", mediaType);
                    [self showCamera];
                }
                else {
                    NSLog(@"Not granted access to %@", mediaType);
                }
                
            }];
        }else {
            NSLog(@"Unknown authorization status");
        }
    }else{
        [self showCamera];
    }
}
//成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]&&picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        //获取照片的原图
//        UIImage* original = [info objectForKey:UIImagePickerControllerOriginalImage];
        //获取图片裁剪的图
        edit = [info objectForKey:UIImagePickerControllerEditedImage];
//        //获取图片裁剪后，剩下的图
//        UIImage* crop = [info objectForKey:UIImagePickerControllerCropRect];
//        //获取图片的url
//        NSURL* url = [info objectForKey:UIImagePickerControllerMediaURL];
//        //获取图片的metadata数据信息
//        NSDictionary* metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
        //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
//        UIImageWriteToSavedPhotosAlbum(edit, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        [photo setBackgroundImage:edit forState:UIControlStateNormal];
        [photo setBackgroundImage:edit forState:UIControlStateHighlighted];
        photo.userInteractionEnabled = YES;
    }else{
        
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//取消照相机的回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    NSLog(@"saved..");
}
-(void)showCamera{
    UIImagePickerController *imagepicker =  [[UIImagePickerController alloc] init];
    //指定使用照相机模式,可以指定使用相册／照片库
    imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //设置当拍照完或在相册选完照片后，是否跳到编辑模式进行图片剪裁。只有当showsCameraControls属性为true时才有效果
    imagepicker.allowsEditing = YES;
    //设置拍照时的下方的工具栏是否显示，如果需要自定义拍摄界面，则可把该工具栏隐藏
    imagepicker.showsCameraControls  = YES;
    //设置使用后置摄像头，可以使用前置摄像头
    imagepicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    //设置闪光灯模式
    /*
     typedef NS_ENUM(NSInteger, UIImagePickerControllerCameraFlashMode) {
     UIImagePickerControllerCameraFlashModeOff  = -1,
     UIImagePickerControllerCameraFlashModeAuto = 0,
     UIImagePickerControllerCameraFlashModeOn   = 1
     };
     */
    imagepicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    //设置相机支持的类型，拍照和录像
//    imagepicker.mediaTypes = @[(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie];
    imagepicker.mediaTypes = @[(NSString*)kUTTypeImage];
    //设置拍摄时屏幕的view的transform属性，可以实现旋转，缩放功能
    // imagepicker.cameraViewTransform = CGAffineTransformMakeRotation(M_PI*45/180);
    // imagepicker.cameraViewTransform = CGAffineTransformMakeScale(1.5, 1.5);
    //所有含有cameraXXX的属性都必须要sourceType是UIImagePickerControllerSourceTypeCamera时设置才有效果，否则会有异常
    //设置UIImagePickerController的代理
    imagepicker.delegate = self;
    [self presentViewController:imagepicker animated:YES completion:^{
        
    }];
}
//-(void)voiceBtnClicked:(UIButton *)sender{
//    [self startListenning:sender];
//}
-(UIButton *)MyBtn:(CGRect)rect title:(NSString *)title nomarlName:(NSString *)photoH nomarlName:(NSString *)photo_{
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *h = [ApplicationUtils getLocalImage:photoH];
    UIImage *p = [ApplicationUtils getLocalImage:photo_];
    [photoBtn setImage:h forState:UIControlStateNormal];
    [photoBtn setImage:p forState:UIControlStateHighlighted];
    [photoBtn.layer setBorderColor:KColor.CGColor];
    [photoBtn.layer setBorderWidth:1.0];
    [photoBtn.layer setCornerRadius:4.0];
    [photoBtn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 45.0, 20.0, 0.0)];
    [photoBtn setTitleEdgeInsets:UIEdgeInsetsMake(40.0, -21.0, 0.0, 10.0)];
    [photoBtn setFrame:rect];
    [photoBtn setTitleColor:KColor forState:UIControlStateNormal];
    [photoBtn setTitleColor:KColor forState:UIControlStateHighlighted];
    [photoBtn setTitle:title forState:UIControlStateNormal];
    [photoBtn setTitle:title forState:UIControlStateHighlighted];
    [photoBtn.titleLabel setFont:[UIFont systemFontOfSize:12.0]];
    return photoBtn;
}
-(void)initSelfView{
    self.titleLabel.text = @"答  案";
    UIButton *photoBtn = [self MyBtn:CGRectMake(10, FMScreenHeight-114-20, 24.0*6, 19.0*6) title:@"添加图片"nomarlName:@"takePhotoClicked@2x" nomarlName:@"takePhotoNormal@2x"];
    [photoBtn addTarget:self action:@selector(photoBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:photoBtn];
    
    UIButton *voiceBtn = [self MyBtn:CGRectMake(FMSCREENWIDTH-24.0*6-10,FMScreenHeight-114-20, 24.0*6, 19.0*6) title:@"语音输入"nomarlName:@"voiceClicked@2x" nomarlName:@"voiceNormal@2x"];
    [voiceBtn addTarget:self action:@selector(voiceBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:voiceBtn];
    
    UILabel *layerView = [[UILabel alloc] initWithFrame:CGRectMake(10, FMStatuesHeight+FMNavHeight+10, FMScreenWidth-20, 150)];
    layerView.layer.cornerRadius = 10.0;
    layerView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    layerView.layer.borderWidth = 1.0;
    [self.view addSubview:layerView];
    
    
    textView = [[UITextView alloc] initWithFrame:CGRectMake(12, FMStatuesHeight+FMNavHeight+12, FMScreenWidth-24, 143)];
    textView.text = @"开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子开始的日子";
    textView.delegate = self;
    [self.view addSubview:textView];
    
    photo = [UIButton buttonWithType:UIButtonTypeCustom];
    [photo setFrame:CGRectMake(12.0+72.0, FMStatuesHeight+FMNavHeight+12+152, FMScreenWidth-84*2, 190.0)];
    [photo setBackgroundImage:[ApplicationUtils getLocalImage:@"takePhotoClicked@2x"] forState:UIControlStateNormal];
    [photo setBackgroundImage:[ApplicationUtils getLocalImage:@"takePhotoClicked@2x"] forState:UIControlStateHighlighted];
    photo.userInteractionEnabled = NO;
    [photo addTarget:self action:@selector(photoClicked:) forControlEvents:UIControlEventTouchUpInside];
    [photo setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:photo];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 0.8; //定义按的时间
    [photo addGestureRecognizer:longPress];
}
-(void)photoImageClicked:(UIButton *)sender{
    [UIView animateWithDuration:0.5 animations:^{
        [sender setFrame:photo.frame];
    } completion:^(BOOL finished) {
        if (finished) {
            [sender removeFromSuperview];
        }
    }];
}
-(void)photoClicked:(UIButton *)sender{
    sender.selected = !sender.selected;
    if(sender.selected){
        [UIView animateWithDuration:0.5 animations:^{
            [sender setFrame:self.view.bounds];
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            [sender setFrame:CGRectMake(12.0+72.0, FMStatuesHeight+FMNavHeight+12+152, FMScreenWidth-84*2, 190.0)];
        }];
    }
}
-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        NSLog(@"长按事件");
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"消息" message:@"确定删除该照片吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            photo.userInteractionEnabled = NO;
            [photo setBackgroundImage:[ApplicationUtils getLocalImage:@"takePhotoClicked@2x"] forState:UIControlStateNormal];
            [photo setBackgroundImage:[ApplicationUtils getLocalImage:@"takePhotoClicked@2x"] forState:UIControlStateHighlighted];
        }
            break;
        default:
            break;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //[self initSelfView];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}
-(BOOL)textView:(UITextView *)textView_ shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView_ resignFirstResponder];
        return NO;
    }
    return YES;
}
-(BOOL)prefersStatusBarHidden{
    return NO;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
@end
